package org.huamoxi.config;

import org.huamoxi.filter.TokenCheckFilter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
import org.springframework.security.oauth2.provider.token.ResourceServerTokenServices;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.annotation.Resource;

@Configuration
@EnableResourceServer // 开启资源服务器认证
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
    @Resource
    TokenCheckFilter tokenCheckFilter;
    @Resource(name = "jwtTokenStore")
    TokenStore jwtTokenStore;

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.addFilterBefore(tokenCheckFilter, UsernamePasswordAuthenticationFilter.class);
        http.csrf().disable();
        // 请求拦截
        http.authorizeRequests().anyRequest().authenticated();
    }

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) {
        resources.resourceId("res_art_1");
    }

    @Bean
    ResourceServerTokenServices tokenService() {
        DefaultTokenServices services = new DefaultTokenServices();
        services.setTokenStore(jwtTokenStore);
        return services;
    }
}
